import React, {Component} from 'react';
import {
    View,
    Text,
    ScrollView,
    DatePickerIOS,
    TouchableOpacity,
    Dimensions,
    StyleSheet,
} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import AllStyle from '../../../../../style';
import {HeaderTitle} from '../../../../../componet/settingComponent/HeaderTitle';
import {CardItem} from '../../../../../componet/settingComponent/CardItem';
import {BrLine} from '../../../../../componet/settingComponent/BrLine';
import {BottomButton} from '../../../../../componet/settingComponent/BottomButton';
import {Drawer} from '../../../../../componet/Drawer';
import DatePicker from 'react-native-date-picker';
import {CardItemSwitch} from '../../../../../componet/settingComponent/CardItemSwitch';
import {getTimer} from '../../../../../utils/DateUtils';
import {preventDoubleClick} from '../../../../../utils/preventDoubleClick';
import {Toast} from '../../../../../utils/Toast';
import {removeToken} from '../../../../../utils/Auth';
import {saveClasses, getClassesInfoById, delClassesById} from '../../../../../api/classes';
import {Loading} from '../../../../../utils/Loading';


const height = Dimensions.get('window').height;
const width = Dimensions.get('window').width;

export class SaveClassScreen extends Component {
    constructor(props) {
        super(props);

        this.state = {
            title: this.props.route.params.title,
            visible: false,
            chosenDate: new Date(),
            //用于存储选择了哪个时间
            dateName: null,
            isHighSetting: false,
            isRes: false,
            classes: {
                classesId: this.props.route.params.classesId == null ? '' : this.props.route.params.classesId,
                classesName: '',
                workStartTime: null,
                workEndTime: null,
                workStartTimeUpLimit: null,
                workEndTimeLowerLimit: null,
                restStartTime: null,
                restEndTime: null,
            },
        };
        this.setDate = this.setDate.bind(this);
    }

    //生命周期：组件挂载后
    componentDidMount() {
        //获取班次信息
        this.getClassesInfo();
    }

    componentDidUpdate(oldProps) {
        // 比较前后props
        if (this.props.route.params != oldProps.route.params) {
            let classes = this.state.classes;
            classes.classesName = this.props.route.params.Name;
            this.setState({
                classes,
            });
        }

    }

    //选择时间
    choseTime = (dateName) => {
        let classes = this.state.classes;

        if (classes[dateName]) {
            let date = '2022/01/01 ' + classes[dateName];

            this.setState({chosenDate: new Date(date)});
        } else {
            this.setState({chosenDate: new Date()});
        }
        this.setState({dateName: dateName});

        this.setState({visible: true});
    };

    setDate(newDate) {
        this.setState({chosenDate: newDate});
    }

    //确认时间
    drSave = () => {
        let dateName = this.state.dateName;
        let classes = this.state.classes;
        let time = this.state.chosenDate;
        classes[dateName] = getTimer(time);
        this.setState({classes: classes});
        this.setState({visible: false});
    };
    //高级打卡按钮变化时
    onIsHighSettingValueChange = () => {
        const is = this.state.isHighSetting == true ? false : true;
        this.setState({isHighSetting: is});
    };
    goto = () => {
        const route = {
            name: 'SetName',
            params: {
                title: '班次名称',
                Name: this.state.classes.classesName,
                routePathName:'SaveClass'
            },
        };
        this.props.navigation.navigate(route);
    };

    goBack = () => {
        const route={
            name:'ClassesManege',
            params: {
                title: '班次管理',
                action:'',
            },
        }
        this.props.navigation.navigate(route);
    };


    Drhide = () => {
        this.setState({visible: false});
    };

    onValueChange = () => {
        const is = this.state.isRes == true ? false : true;
        this.setState({isRes: is});
    };
    //保存班次
    save = () => {
        //数据校验

        let classes = {
            classesId: this.state.classes.classesId,
            classesName: this.state.classes.classesName,
            workStartTime: this.state.classes.workStartTime,
            workEndTime: this.state.classes.workEndTime,
            workStartTimeUpLimit: this.state.classes.workStartTimeUpLimit,
            workEndTimeLowerLimit: this.state.classes.workEndTimeLowerLimit,
            restStartTime: this.state.classes.restStartTime,
            restEndTime: this.state.classes.restEndTime,
        };
        if (classes.classesName == null || classes.classesName == '') {
            Toast.showWarning('班次名称不能为空');
            return;
        } else if (classes.workStartTime == null || classes.workEndTime == null) {
            Toast.showWarning('请设置上下班打卡时间');
            return;
        } else if (classes.workStartTime > classes.workEndTime) {
            Toast.showWarning('下班时间应该在上班时间之后');
            return;

        }
        if (this.state.isHighSetting == true) {
            if (classes.workStartTimeUpLimit == null || classes.workEndTimeLowerLimit == null) {
                Toast.showWarning('下班最大时间和上班最大时间不能为空');
                return;
            } else if (classes.workStartTimeUpLimit > classes.workEndTimeLowerLimit) {
                Toast.showWarning('下班最大时间应该在上班最大时间之后');
                return;
            } else if (classes.workStartTime < classes.workStartTimeUpLimit) {
                Toast.showWarning('上班最大时间应该在上班时间之前');
                return;
            } else if (classes.workEndTimeLowerLimit < classes.workEndTime) {
                Toast.showWarning('下班最大时间应该在下班时间之后');
                return;
            }
        } else {
            classes.workStartTimeUpLimit = null;
            classes.workEndTimeLowerLimit = null;
        }
        if (this.state.isRes == true) {

            if (classes.restStartTime == null || classes.restEndTime == null) {
                Toast.showWarning('休息开始、结束时间不能为空');
                return;
            } else if (classes.restStartTime > classes.restEndTime) {
                Toast.showWarning('休息结束时间应该在休息开始时间之后');
                return;
            } else if (!(classes.workStartTime < classes.restStartTime && classes.restStartTime < classes.workEndTime)) {
                Toast.showWarning('休息开始时间要在工作时间段内');
                return;
            } else if (classes.restEndTime < classes.workStartTime || classes.restEndTime > classes.workEndTime) {
                Toast.showWarning('休息结束时间要在工作时间段内');
                return;
            }
        } else {
            classes.restStartTime = null;
            classes.restEndTime = null;
        }

        Loading.show();
        saveClasses(classes).then(
            res => {
                Loading.hidden();
                if (res.code == 0) {
                    this.goBack();

                } else {
                    Toast.showWarning(res.msg);
                }

            },
        ).catch(err => {
            Loading.hidden();
            alert(err);
        }).finally(()=>{
            Loading.hidden();
        });


    };
    //获取详细详细
    getClassesInfo = () => {
        let id = this.state.classes.classesId;
        if (id == null || id == '') {
            return;
        }
        Loading.show();
        getClassesInfoById(id).then(res => {
            Loading.hidden();
            let {classes} = res;
            if (classes.restStartTime != null) {
                this.setState({isRes: true});
            }
            if (classes.workStartTimeUpLimit != null) {
                this.setState({isHighSetting: true});
            }

            classes = {
                classesId: classes.classesId,
                classesName: classes.classesName,
                workStartTime: classes.workStartTime,
                workEndTime: classes.workEndTime,
                workStartTimeUpLimit: classes.workStartTimeUpLimit,
                workEndTimeLowerLimit: classes.workEndTimeLowerLimit,
                restStartTime: classes.restStartTime,
                restEndTime: classes.restEndTime,
            };
            this.setState({classes: classes});


        }).catch(err => {
            Loading.hidden();
            alert(err);
        }).finally(()=>{
            Loading.hidden();
        });
    };
    delClasses = () => {
        let id = this.state.classes.classesId;
        if (id == null || id == '') {
            alert()
            return;
        }

        Loading.show();
        delClassesById(id).then(res => {
            Loading.hidden();
            this.goBack();
        }).catch(err => {
                Loading.hidden();
                //alert(err)
                Toast.showWarning(err.toString());
            },
        ).finally(()=>{
            Loading.hidden();
        });
    };

    render() {
        if (this.state.classesId) {

        }
        return (
            <SafeAreaView edges={['top', 'left', 'right', 'bottom']} style={{flex: 1, backgroundColor: '#FFF'}}>
                <View style={AllStyle.container}>
                    <HeaderTitle goBack={() => this.goBack()} headtitle={this.state.title}></HeaderTitle>
                    <ScrollView style={AllStyle.padding15}>
                        <View style={AllStyle.card}>
                            <TouchableOpacity onPress={() => this.goto('班次名称')}>
                                <CardItem title="班次名称"
                                          value={this.state.classes.classesName == '' ? '未设置' : this.state.classes.classesName}>
                                </CardItem>
                            </TouchableOpacity>

                        </View>

                        <View style={AllStyle.card}>
                            <TouchableOpacity onPress={() => {
                                // 传输对象名称
                                this.choseTime('workStartTime');
                            }}>
                                <CardItem title="上班打卡"
                                          value={this.state.classes.workStartTime == null ? '未设置' : this.state.classes.workStartTime.substring(0, 5)}>
                                </CardItem>
                            </TouchableOpacity>

                            <BrLine></BrLine>
                            <TouchableOpacity onPress={() => {
                                // 传输对象名称
                                this.choseTime('workEndTime');
                            }}>
                                <CardItem title="下班打卡"
                                          value={this.state.classes.workEndTime == null ? '未设置' : this.state.classes.workEndTime.substring(0, 5)}>
                                </CardItem>
                            </TouchableOpacity>
                            <BrLine></BrLine>
                            <CardItemSwitch title="上下班打卡高级设置" onValueChange={() => {
                                this.onIsHighSettingValueChange();
                            }} value={this.state.isHighSetting}></CardItemSwitch>
                            {
                                this.state.isHighSetting == true ? (
                                    <View>
                                        <BrLine></BrLine>
                                        <TouchableOpacity onPress={() => {
                                            // 传输对象名称
                                            this.choseTime('workStartTimeUpLimit');
                                        }}>
                                            <CardItem title="上班最大打卡时段"
                                                      value={this.state.classes.workStartTimeUpLimit == null ? '未设置' : this.state.classes.workStartTimeUpLimit.substring(0, 5)}>
                                            </CardItem>
                                        </TouchableOpacity>
                                        <BrLine></BrLine>
                                        <TouchableOpacity onPress={() => {
                                            // 传输对象名称
                                            this.choseTime('workEndTimeLowerLimit');
                                        }}>
                                            <CardItem title="下班最大打卡时段"
                                                      value={this.state.classes.workEndTimeLowerLimit == null ? '未设置' : this.state.classes.workEndTimeLowerLimit.substring(0, 5)}>
                                            </CardItem>
                                        </TouchableOpacity>
                                    </View>
                                ) : (
                                    <View>
                                    </View>
                                )
                            }
                        </View>
                        <View style={AllStyle.card}>
                            <CardItemSwitch title="开启休息时间" onValueChange={() => {
                                this.onValueChange();
                            }} value={this.state.isRes}></CardItemSwitch>
                            {
                                this.state.isRes == true ? (
                                    <View>
                                        <BrLine></BrLine>
                                        <TouchableOpacity onPress={() => {
                                            // 传输对象名称
                                            this.choseTime('restStartTime');
                                        }}>
                                            <CardItem title="午休开始"
                                                      value={this.state.classes.restStartTime == null ? '未设置' : this.state.classes.restStartTime.substring(0, 5)}>
                                            </CardItem>
                                        </TouchableOpacity>
                                        <BrLine></BrLine>
                                        <TouchableOpacity onPress={() => {
                                            // 传输对象名称
                                            this.choseTime('restEndTime');
                                        }}>
                                            <CardItem title="午休结束"
                                                      value={this.state.classes.restEndTime == null ? '未设置' : this.state.classes.restEndTime.substring(0, 5)}>
                                            </CardItem>
                                        </TouchableOpacity>
                                    </View>
                                ) : (
                                    <View>
                                    </View>
                                )
                            }

                        </View>
                        {
                            this.state.classes.classesId != '' ?
                                (
                                    <TouchableOpacity onPress={() => {
                                        this.delClasses();
                                    }}>
                                        <View style={AllStyle.card}>
                                            <Text style={style.del}>删除班次</Text>
                                        </View>
                                    </TouchableOpacity>
                                ) : (<View></View>)
                        }
                    </ScrollView>
                    <Drawer visible={this.state.visible} onShow={() => this.drSave()} dismiss={() => this.Drhide()}>
                        <DatePicker
                            style={style.date}
                            mode='time'
                            locale="zh_GB"
                            date={this.state.chosenDate}
                            onDateChange={this.setDate}
                        ></DatePicker>
                    </Drawer>

                    <BottomButton click={() => {
                        preventDoubleClick(this.save);
                    }} title='保存'></BottomButton>
                </View>
            </SafeAreaView>
        );
    }
}


const style = StyleSheet.create({
    //样式
    drawer: {
        position: 'absolute',
        bottom: 0,
        width: width,
        paddingBottom: 20,
        backgroundColor: '#FFF',
    },
    drawerTop: {
        display: 'flex',
        flexDirection: 'row',
        padding: 10,
        justifyContent: 'space-between',
        borderBottom: 30,
    },
    date: {
        width: width,
    },
    del: {
        textAlign: 'center',
        // display: 'flex',
        // alignItems: 'center',
        // justifyContent: 'center',
        color: '#FB5F2D',
        fontSize: 16,
        paddingTop: 15,
        paddingBottom: 15,
        paddingRight: 15,

    },

});
